package com.gexiaobao.pigeon.ui.fragment.mall.evaluate

import android.net.Uri
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.model.bean.ImageModel
import com.gexiaobao.pigeon.app.model.param.EvaluateParam
import com.gexiaobao.pigeon.app.rxui.tablayout.listener.GlideEngine
import com.gexiaobao.pigeon.app.util.PictureUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.databinding.FragmentEvaluateBinding
import com.gexiaobao.pigeon.viewmodel.EvaluateViewModel
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.style.PictureSelectorStyle
import com.zs.easy.imgcompress.EasyImgCompress
import com.zs.easy.imgcompress.listener.OnCompressSinglePicListener
import com.zs.easy.imgcompress.util.GBMBKBUtil
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import java.io.File

/**
 * @Author      : hxw
 * @Date        : 2023/6/27 15:42
 * @Describe    : 评价
 */
class FragmentEvaluate : BaseFragment<EvaluateViewModel, FragmentEvaluateBinding>() {

    private var goodsRating: Int = 5
    private var logisticsRating: Int = 0
    private var courierRating: Int = 0
    private var packageRating: Int = 0
    private var mRealPath: String = ""
    private var mapImageId: MutableMap<Int, Int> = mutableMapOf()
    private var goodId = 0
    private var orderId = 0
    private var specName = ""

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.includeBar.tvWhiteTitle.text = getString(R.string.shop_evaluate)
        goodId = requireArguments().getInt("goodId")
        orderId = requireArguments().getInt("orderId")
        specName = arguments?.getString("specName").toString()

        mDatabind.starEvaluate.setOnRatingChangeListener {
            goodsRating = it.toInt()
            mDatabind.tvEvaluateLev.text = when (it) {
                1f -> getString(R.string.very_bad)
                2f -> getString(R.string.bad)
                3f -> getString(R.string.ordinary)
                4f -> getString(R.string.good)
                5f -> getString(R.string.very_good)
                else -> ""
            }
        }
        mDatabind.starPackaging.setOnRatingChangeListener {
            packageRating = it.toInt()
        }
        mDatabind.starDeliverySpeed.setOnRatingChangeListener {
            logisticsRating = it.toInt()
        }
        mDatabind.starService.setOnRatingChangeListener {
            courierRating = it.toInt()
        }

        mDatabind.uploadMultiImageView
            .setImageInfoList(null)
            // 所有属性都可以在代码中再设置
            // 不开启拖拽排序
            .setDrag(false)
            // 设置每行3列
            .setColumns(3)
            // 显示新增按钮
            .setShowAdd(true)
            // 设置图片缩放类型 (默认 CENTER_CROP)
            .setScaleType(ImageView.ScaleType.CENTER_CROP)
            // item点击回调
            .setImageItemClickListener { _ ->

            }
            // 设置删除点击监听（如果不设置，测试默认移除数据），自己处理数据删除过程
            .setDeleteClickListener { multiImageView, position ->
                context?.let {
                    AlertDialog.Builder(it)
                        .setTitle(getString(R.string.delete))
                        .setMessage(getString(R.string.sure_delete_pic))
                        .setNegativeButton(getString(R.string.sure)) { dialog, _ ->
                            dialog.dismiss()
                            multiImageView.deleteItem(position)
                            mapImageId.remove(position)
                        }
                        .show()
                }
            }
            // 图片加载
            .setImageViewLoader { _, path, imageView ->
                // （这里自己选择图片加载框架，不做限制）
                imageView.setImageURI(Uri.parse("file://$path"))
            }
            // 新增按钮点击回调
            .setAddClickListener {
                selectEvaluateImage()
//                requestPermission()
            }
            .show()
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvSubmitEvaluate, mDatabind.includeBar.ivBack) {
            when (it) {
                mDatabind.includeBar.ivBack -> {
                    nav().navigateUp()
                }

                mDatabind.tvSubmitEvaluate -> {
                    submitEvaluateData()
                }
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        var index = 0
        mViewModel.evaluateImageResult.observe(viewLifecycleOwner) {
            if (it != null) {
                addNewData(mRealPath)
                RxToast.showToast(getString(R.string.upload_successful))
                mapImageId[index] = it.id
                index++
            }
        }
        mViewModel.evaluateResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it.isSuccess) {
                RxToast.showToast(getString(R.string.Success_Evaluation))
                nav().navigateUp()
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
    }

    private fun submitEvaluateData() {
        val sb = StringBuffer()
        mapImageId.forEach {
            sb.append(it.value.toString() + ",")
        }
        val imageId = sb.toString()
        val mImages = if (imageId.isNotEmpty()) {
            imageId.subSequence(0, imageId.length - 1).toString()
        } else {
            ""
        }
        val body = EvaluateParam(
            goodsId = goodId,
            orderId = orderId,
            goodsEvaluate = mDatabind.etEvaluateContent.text.toString().trim(),
            goodsRating = goodsRating,
            logisticsRating = logisticsRating,
            courierRating = courierRating,
            packageRating = packageRating,
            specName = specName,
            images = mImages
        )
        showLoading(getString(R.string.loading))
        mViewModel.addGoodsReviews(body)
    }

    private fun selectEvaluateImage() {
        val selectionModel: PictureSelectionModel = PictureSelector.create(context)
            .openGallery(SelectMimeType.ofImage())
            .setSelectorUIStyle(PictureSelectorStyle())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setSelectionMode(SelectModeConfig.SINGLE)
            .setCameraInterceptListener(PictureUtil.getCustomCameraEvent())
            .isLoopAutoVideoPlay(false)
            .isPageSyncAlbumCount(true)
            .setLanguage(LanguageConfig.SYSTEM_LANGUAGE)
            .setQuerySortOrder("")
            .isDisplayCamera(true)
            .isOpenClickSound(true)
            .isPreviewImage(false)
            .isMaxSelectEnabledMask(false)
            .isDirectReturnSingle(false)
            .setMaxSelectNum(1)
            .isDirectReturnSingle(true)
        selectionModel.forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                mRealPath = result!![0].realPath
                // 把单张图片压缩到1024k以内 同时像素不超过1200（宽、高都不大于1200）
                EasyImgCompress.withSinglePic(context, result[0].realPath)
                    .maxPx(1200)
                    .maxSize(1024)
                    .enableLog(true)
                    .setOnCompressSinglePicListener(object : OnCompressSinglePicListener {
                        override fun onStart() {
                            LogUtils.debugInfo("onStart")
                        }

                        override fun onSuccess(file: File) {
                            showLoading(getString(R.string.loading))
                            mViewModel.uploadFile(file)
                            LogUtils.debugInfo("onSuccess size = " + GBMBKBUtil.getSize(file.length()) + " getAbsolutePath= " + file.absolutePath)
                        }

                        override fun onError(error: String) {
                            LogUtils.debugInfo("onError error = $error")
                        }
                    }).start()

            }

            override fun onCancel() {}
        })
    }

    private fun addNewData(realPath: String?) {
        val tempList: MutableList<ImageModel> = ArrayList()
        val model = ImageModel()
        model.path = realPath
        tempList.add(model)
        // 调用新增数据
        mDatabind.uploadMultiImageView.addNewData(tempList.toList())
    }
}
